// src/main/java/com/easy/gateway/filter/GatewayGlobalFilter.java
package com.easy.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.easy.common.service.ITokenService;
import com.easy.common.util.Result;
import com.easy.common.util.SYS;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

@Component
public class GatewayGlobalFilter implements GlobalFilter, Ordered {
//    @DubboReference
//    ITokenService tokenService;
//
//    // 白名单，放行的地址
//    public static final List<String> ALLOWED_PATHS = Arrays.asList("/login/dologin", "/login/captcha");
//
//    @Override
//    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        System.out.println("GatewayGlobalFilter");
//        ServerHttpRequest request = exchange.getRequest();
//        URI uri = request.getURI();
//        String path = uri.getPath();// 获取请求路径
//
//        if (ALLOWED_PATHS.contains(path)) {
//            // 如果在白名单就放行
//            return chain.filter(exchange);
//        }
//
//        // 验证是否登录
//        String token = request.getHeaders().getFirst(SYS.TOKEN_AUTHORIATION);
//        // 验证token是否为空及有效性
//        if (token == null || !tokenService.checkToken(token)) {
//            return unauthorizedResponse(exchange, Result.fail(401, "未认证"));
//        }
//
//        // 验证通过，继续执行过滤链
//        return chain.filter(exchange);
//    }
// 增加 Dubbo 引用检查，避免空指针
    @DubboReference(check = false) // 允许服务启动时不检查依赖
    ITokenService tokenService;

    // 白名单，支持通配符匹配
    public static final List<String> ALLOWED_PATHS = Arrays.asList(
            "/login/dologin",
            "/login/captcha",
            "/login/register",
            "/concert/search",
            "/concert/recommend",
            "/seatprice/getbyseatid",
            "/user/getid/{id}"
    );

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();

        // 检查是否在白名单（支持通配符）
        if (isAllowed(path)) {
            return chain.filter(exchange);
        }

        // 验证 tokenService 是否可用
        if (tokenService == null) {
            return unauthorizedResponse(exchange, Result.fail(500, "认证服务不可用"));
        }

        // 验证 token
        String token = request.getHeaders().getFirst(SYS.TOKEN_AUTHORIATION);
        if (token == null || !tokenService.checkToken(token)) {
            return unauthorizedResponse(exchange, Result.fail(401, "未认证token"));
        }

        return chain.filter(exchange);
    }
    private static boolean isAllowed(String path) {
          //判断路径
            if (ALLOWED_PATHS.contains(path)) {
                return true;
            }

        return false;
    }

    public static void main(String[] args) {
        String path="/login/captcha";
        Boolean a=isAllowed(path);
        System.out.println(a);
    }


    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, Result result) {
        String json = JSON.toJSONString(result);
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(response.bufferFactory()
                .wrap(json.getBytes(StandardCharsets.UTF_8))));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}